//
//  SBStepScrollView.m
//  TYCyclePagerViewDemo
//
//  Created by 黄建华 on 2018/1/16.
//  Copyright © 2018年 tany. All rights reserved.
//

#import "SBStepScrollView.h"

#define SSWIDTH  [UIScreen mainScreen].bounds.size.width
#define SSHEIGHT [UIScreen mainScreen].bounds.size.height
@implementation SBStepScrollView

/*
 // Only override drawRect: if you perform custom drawing.
 // An empty implementation adversely affects performance during animation.
 - (void)drawRect:(CGRect)rect {
 // Drawing code
 }
 */

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        [self creatView];
    }
    return self;
}

- (void)creatView {
    NSMutableArray *sportArray = [NSMutableArray array];
    for (int i = -29; i <= 0; i++) {
        NSString            *lastStr = [[[NSDate date] dateAfterDay:i] dateToDayString];
        NSMutableDictionary *dic1    = [NSMutableDictionary dictionary];
        [dic1 setObject:StrByInt(0) forKey:@"steps"];
        [dic1 setObject:StrByInt(0) forKey:@"calors"];
        [dic1 setObject:StrByInt(0) forKey:@"distances"];
        [dic1 setObject:StrByInt(10000) forKey:@"steptarget"];
        [dic1 setObject:StrByInt(0) forKey:@"durations"];
        [dic1 setObject:lastStr forKey:@"datestring"];
        [sportArray addObject:dic1];
    }
    _datas = [NSMutableArray arrayWithArray:sportArray];
    [self addPagerView];
    [self layoutSubviews];
    [_pagerView reloadData];
    [self updateScrollViewLabel];
    [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(delayUpdatePageViewInit) object:nil];
    [self performSelector:@selector(delayUpdatePageViewInit) withObject:nil afterDelay:0.05];
}

- (void)delayUpdatePageViewInit {
    _currentMoveIndex = 30 - 1;
    [_pagerView scrollToItemAtIndex:_currentMoveIndex animate:NO];
    [self updateLabelValue:_currentMoveIndex];
}

// 数据更新
- (void)loadDataWithModel:(FriendModel *)model {
    NSArray *array = [NSArray arrayWithArray:model.stepHistory];
    for (int i = 0; i <_datas.count; i++) {
        NSDictionary * localDic = [_datas objectAtIndex:i];
        NSString *localDicDateString = localDic[@"datestring"];
        
        for (NSDictionary *dic in array) {
            NSString *dicDateString = dic[@"datestring"];
            if ([localDicDateString isEqualToString:dicDateString]) {
                [_datas replaceObjectAtIndex:i withObject:dic];
                break;
            }
        }
    }

    [self addPagerView];
    [self layoutSubviews];
    [_pagerView reloadData];
    [self updateScrollViewLabel];
    [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(delayUpdatePageViewInit) object:nil];
    [self performSelector:@selector(delayUpdatePageViewInit) withObject:nil afterDelay:0.05];
}

// 30天日期
- (void)updateScrollViewLabel {
    
    NSMutableArray *dateArray = [[NSMutableArray alloc] init];
    
    [dateArray addObject:@""];
    [dateArray addObject:@""];
    [dateArray addObject:@""];
    for (int i = -29; i <= 0; i++) {
        NSString *lastStr = [[[NSDate date] dateAfterDay:i] dateMonthAndDay];
        [dateArray addObject:lastStr];
    }
    [dateArray addObject:@""];
    [dateArray addObject:@""];
    [dateArray addObject:@""];
    
    for (int i = 0; i < dateArray.count; i++) {
        NSString *date   = [dateArray objectAtIndex:i];
        UIButton *button = [[UIButton alloc] init];
        button.tag             = 100+i;
        button.backgroundColor = [UIColor colorFromHex:0xd7d8d9];
        //日期不要年
        [button setTitle:date forState:UIControlStateNormal];
        button.titleLabel.font = SNFONT(13);
        [button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [button setTitleColor:[UIColor blackColor] forState:UIControlStateSelected];
        
        button.frame = SNFRAME(screenWidth/7.0 *i, 0, screenWidth / 7.0, 40);
        [_labelScrollView addSubview:button];
        if (date.length > 0) {
            [button addTarget:self action:@selector(buttonLabelClick:) forControlEvents:UIControlEventTouchUpInside];
        }
    }
    CGFloat width = dateArray.count / 7 * screenWidth + (dateArray.count) %7 * screenWidth/7;
    _labelScrollView.decelerationRate = 0.9;
    _labelScrollView.contentSize      = CGSizeMake(width, 0);
    _labelScrollView.contentOffset    = CGPointMake(width, 0);
    _updateIndex                      = 29;
}

// 更新卡路里 距离
- (void)updateLabelValue:(NSInteger)selectIndex {
    NSDictionary *dic     = [NSDictionary dictionary];
    if (selectIndex < _datas.count) {
        dic = [_datas objectAtIndex:selectIndex];
    }
    NSInteger    distances = [dic[@"distances"]integerValue]/10*10;
    NSInteger    calors    = [dic[@"calors"]integerValue];
    
    _distanceLabel.text = SN_USER.isMetricSystem ? [NSString stringWithFormat:@"%.2f %@", roundf(1.0*distances*0.0006214*100)/100, SN_Text(@"英里")] : [NSString stringWithFormat:@"%.2f %@", 1.0* distances/1000, SN_Text(@"千米")];
    _calorLabel.text    = [NSString stringWithFormat:@"%d %@", calors, SN_Text(@"大卡")];
}

//更新UI
- (void)buttonTitleUpdate:(NSInteger)selectIndex {
    for (UIButton *button in _labelScrollView.subviews) {
        if ([button isKindOfClass:[UIButton class]]) {
            if (button.tag -100 -3 == selectIndex) {
                button.selected = YES;
                NSString *titleString = button.titleLabel.text;
                _dateLabel.text = titleString;
            } else {
                button.selected = NO;
            }
        }
    }
    [self updateLabelValue:selectIndex];
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    CGFloat   width = screenWidth/ 7.0;
    NSInteger index = (NSInteger)((_labelScrollView.contentOffset.x+10)/width);
    
    [_labelScrollView setContentOffset:CGPointMake(width*index*1.0, 0) animated:YES];
    [self buttonTitleUpdate:index];
    [self labelControlWith:index];
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate {
    CGFloat   width = screenWidth/ 7.0;
    NSInteger index = (NSInteger)((_labelScrollView.contentOffset.x+10)/width);
    
    [_labelScrollView setContentOffset:CGPointMake(width*index*1.0, 0) animated:YES];
    [self buttonTitleUpdate:index];
    [self labelControlWith:index];
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    CGFloat   width = screenWidth/ 7.0;
    NSInteger index = (NSInteger)((_labelScrollView.contentOffset.x+10)/width);
    
    _updateIndex = index;
    [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(delayUPdateButton) object:nil];
    [self performSelector:@selector(delayUPdateButton) withObject:nil afterDelay:0.02];
    [self labelControlWith:index];
}

- (void)delayUPdateButton {
    for (UIButton *button in _labelScrollView.subviews) {
        if ([button isKindOfClass:[UIButton class]]) {
            if (button.tag -100 -3 == _updateIndex) {
                button.selected = YES;
                NSString *titleString = button.titleLabel.text;
                _dateLabel.text = titleString;
            } else {
                button.selected = NO;
            }
        }
    }
}

- (void)buttonLabelClick:(UIButton *)sender {
    CGFloat   width = screenWidth/ 7.0;
    NSInteger index = sender.tag - 100-3;
    
    [_labelScrollView setContentOffset:CGPointMake(width*index*1.0, 0) animated:YES];
    
    [self buttonTitleUpdate:index];
    [self labelControlWith:index];
}

// label控制圆圈
- (void)labelControlWith:(NSInteger)selectIndex {
    _pagerView.delegate = nil;
    [_pagerView scrollToItemAtIndex:selectIndex animate:YES];
    [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(delayUPdatePageView) object:nil];
    [self performSelector:@selector(delayUPdatePageView) withObject:nil afterDelay:0.25];
}

- (void)delayUPdatePageView {
    _pagerView.delegate = self;
}

- (void)layoutSubviews {
    [super layoutSubviews];
    _pagerView.frame              = CGRectMake(0, 0, self.frame.size.width, self.frame.size.height);
    _pagerView.layout.itemSize    = CGSizeMake(self.frame.size.width /3 *0.88, self.frame.size.width /3 *0.88);
    _pagerView.layout.itemSpacing = 15;
    _pagerView.layout.layoutType  = TYCyclePagerTransformLayoutLinear;
    [_pagerView setNeedUpdateLayout];
    
    _labelScrollView.frame                          = SNFRAME(0, _pagerView.height - 80, _pagerView.width, 40);
    _labelScrollView.delegate                       = self;
    _labelScrollView.showsHorizontalScrollIndicator = NO;
    _labelScrollView.showsVerticalScrollIndicator   = NO;
    
    _imageV.frame = SNFRAME(10, 10, 50, 50);
    _imageV.image = [UIImage image:@"步数"];
    
    _type.textColor = [UIColor blackColor];
    _type.frame     = SNFRAME(_imageV.right + 10, _imageV.top + 7, 100, 20);
    _type.font      = SNFONT(16.0);
    _type.text      = SN_Text(@"步数");
    
    _dateLabel.textColor = SNCOLORGRAYLINE;
    _dateLabel.frame     = SNFRAME(_imageV.right + 10, _type.bottom, 100, 20);
    _dateLabel.font      = SNFONT(13.0);
    
    _imageV1.frame = SNFRAME(5, _pagerView.height - 35, 30, 30);
    _imageV1.image = [UIImage image:@"卡路里"];
    
    _info1.textColor = SNCOLORGRAY;
    _info1.text      = [NSString stringWithFormat:@"%@:",SN_Text(@"卡路里")];
    _info1.frame     = SNFRAME(_imageV1.right, _imageV1.top +5, screenWidth/4 -_imageV1.right +25, 20);
    _info1.font      = SNFONT(12.0);
    
    _calorLabel.textColor = SNCOLORBLACK;
    _calorLabel.text      = @"";
    _calorLabel.frame     = SNFRAME(_info1.right-2, _imageV1.top +5, screenWidth/2 - _info1.right, 20);
    _calorLabel.font      = SNFONT(14.0);
    _calorLabel.textAlignment = NSTextAlignmentCenter;
    
    _imageV2.frame = SNFRAME(5 +screenWidth/2, _pagerView.height - 35, 30, 30);
    _imageV2.image = [UIImage image:@"距离"];
    
    _info2.textColor = SNCOLORGRAY;
    _info2.text      = [NSString stringWithFormat:@"%@:",SN_Text(@"距离")];
    _info2.frame     = SNFRAME(_imageV2.right, _imageV2.top +5, _info1.width, 20);
    _info2.font      = SNFONT(12.0);
    
    _distanceLabel.textColor = SNCOLORBLACK;
    _distanceLabel.text      = @"";
    _distanceLabel.textAlignment = NSTextAlignmentCenter;
    _distanceLabel.frame     = SNFRAME(_info2.right-2, _imageV2.top +5, _calorLabel.width, 20);
    _distanceLabel.font      = SNFONT(14.0);
    
    _type.adjustsFontSizeToFitWidth = YES;
    _type.minimumScaleFactor = 0.5;
    _info1.adjustsFontSizeToFitWidth = YES;
    _info1.minimumScaleFactor = 0.5;
    _info2.adjustsFontSizeToFitWidth = YES;
    _info2.minimumScaleFactor = 0.5;
    _calorLabel.adjustsFontSizeToFitWidth = YES;
    _calorLabel.minimumScaleFactor = 0.5;
    _distanceLabel.adjustsFontSizeToFitWidth = YES;
    _distanceLabel.minimumScaleFactor = 0.5;
}

- (void)addPagerView {
    if (_pagerView) {
        _pagerView.delegate = nil;
        [_pagerView removeFromSuperview];
        _pagerView = nil;
    }
    
    _pagerView                   = [[TYCyclePagerView alloc]init];
    _pagerView.layer.borderWidth = 1;
    _pagerView.layer.borderColor = SNCOLORGRAYLINE.CGColor;
    _pagerView.dataSource        = self;
    _pagerView.delegate          = self;
    // registerClass or registerNib
    [_pagerView registerClass:[StepTYCyclePagerViewCell class] forCellWithReuseIdentifier:@"pagerViewcellId"];
    [self addSubview:_pagerView];
    // 是否无限滚
    _pagerView.isInfiniteLoop              = NO;
    _pagerView.autoScrollInterval          = 0;
    _pagerView.layout.itemHorizontalCenter = YES;
    
    _imageV = [[UIImageView alloc] init];
    [_pagerView addSubview:_imageV];
    
    _type = [[UILabel alloc] init];
    [_pagerView addSubview:_type];
    
    _dateLabel = [[UILabel alloc] init];
    [_pagerView addSubview:_dateLabel];
    
    _labelScrollView = [[UIScrollView alloc] init];
    [_pagerView addSubview:_labelScrollView];
    
    _imageV1 = [[UIImageView alloc] init];
    [_pagerView addSubview:_imageV1];
    
    _info1 = [[UILabel alloc] init];
    [_pagerView addSubview:_info1];
    
    _calorLabel = [[UILabel alloc] init];
    [_pagerView addSubview:_calorLabel];
    
    _imageV2 = [[UIImageView alloc] init];
    [_pagerView addSubview:_imageV2];
    
    _info2 = [[UILabel alloc] init];
    [_pagerView addSubview:_info2];
    
    _distanceLabel = [[UILabel alloc] init];
    [_pagerView addSubview:_distanceLabel];
}

#pragma mark - TYCyclePagerViewDataSource

- (NSInteger)numberOfItemsInPagerView:(TYCyclePagerView *)pageView {
    return 30;
}

- (UICollectionViewCell *)pagerView:(TYCyclePagerView *)pagerView cellForItemAtIndex:(NSInteger)index
{
    StepTYCyclePagerViewCell *cell = [pagerView dequeueReusableCellWithReuseIdentifier:@"pagerViewcellId" forIndex:index];
    cell.button.tag = index;
    NSDictionary *dic     = [NSDictionary dictionary];
    if (index < _datas.count) {
        dic = [_datas objectAtIndex:index];
    }
    NSInteger    step       = [dic[@"steps"]integerValue];
    NSInteger    stepTarget = [dic[@"steptarget"]integerValue];
    float        progress   = 1.0 *step/stepTarget;
    if (step >= stepTarget) {
        progress = 1.0;
    }
    cell.stepCircle.ValueLabel.text = StrByInt(step);
    cell.stepCircle.progress        = progress;
    [cell.button addTarget:self action:@selector(buttonClick:) forControlEvents:UIControlEventTouchUpInside];
    return cell;
}

- (void)buttonClick:(UIButton *)sender {
    if (_currentMoveIndex < sender.tag) {
        // 右
        [_pagerView scrollToNearlyIndexAtDirection:TYPagerScrollDirectionRight animate:YES];
    }
    if (_currentMoveIndex > sender.tag) {
        // 左
        [_pagerView scrollToNearlyIndexAtDirection:TYPagerScrollDirectionLeft animate:YES];
    }
    if (_currentMoveIndex == sender.tag) {
    }
    [self updateSelectValue:sender.tag];
}

- (TYCyclePagerViewLayout *)layoutForPagerView:(TYCyclePagerView *)pageView {
    TYCyclePagerViewLayout *layout = [[TYCyclePagerViewLayout alloc]init];
    
    layout.itemSize             = CGSizeMake(CGRectGetWidth(pageView.frame)*0.95, CGRectGetHeight(pageView.frame)*0.95);
    layout.itemHorizontalCenter = YES;
    return layout;
}

- (void)pagerView:(TYCyclePagerView *)pageView didScrollFromIndex:(NSInteger)fromIndex toIndex:(NSInteger)toIndex {
    //    NSLog(@"滑动停止 >>> %ld ->  %ld",fromIndex,toIndex);
    _currentMoveIndex = toIndex;
    [self updateSelectValue:toIndex];
}

- (void)updateSelectValue:(NSInteger)index {
    CGFloat   width     = screenWidth/ 7.0;
    NSInteger moveIndex = index;
    
    [_labelScrollView setContentOffset:CGPointMake(width*moveIndex*1.0, 0) animated:YES];
    [self buttonTitleUpdate:moveIndex];
}

@end
